package com.nit.lab.utils;

import com.nit.lab.dto.system.TokenDTO;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 移动端不进行Token拦截与验证；用户登录不拦截与验证
        if (request.getRequestURL().indexOf("/api/account/kaptcha") != -1
                || request.getRequestURL().indexOf("/api/account/login") != -1
                || request.getRequestURL().indexOf("/api/person/importPerson") != -1
                || request.getRequestURL().indexOf("/api/interface") != -1) {
            response.setHeader("token_status", "ok");
            return true;
        } else {
            // 通过客户端传递的Token参数进行验证，注意header中的属性名要小写
            TokenDTO tokenDTO = JWTUtil.verifyToken(request.getHeader("Access-Token"));
            if (tokenDTO != null && tokenDTO.getAccountId() > 0) {
                response.setHeader("token_status", "ok");
                return true;
            } else {
                response.setHeader("token_status", "no");
                return false;
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
